package com.ruoyi.task.service.impl;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.task.domain.CameraInfo;
import com.ruoyi.task.domain.StreamPictureParams;
import com.ruoyi.task.domain.StreamPictureResult;
import com.ruoyi.task.mapper.CameraInfoMapper;
import com.ruoyi.task.service.ICameraService;
import com.ruoyi.task.service.IHaoYunService;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
public class CameraServiceImpl implements ICameraService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CameraInfoMapper cameraInfoMapper;

    @Autowired
    private IHaoYunService haoYunService;

    @Autowired
    private ISysDeptService deptService;

    @Override
    public List<CameraInfo> queryCameraInfoList(String deptCode) {
        return cameraInfoMapper.selectCameraInfoListByDeptCode(deptCode);
    }

    /**
     * 查询摄像头管理列表
     *
     * @param cameraInfo 摄像头管理
     * @return 摄像头管理
     */
    @Override
    public List<CameraInfo> selectCameraInfoList(CameraInfo cameraInfo) {
        return cameraInfoMapper.selectCameraInfoList(cameraInfo);
    }


    @Override
    public String queryCameraPicture(String cameraId) {
        try {
            // 查询数据库中是否有相应的图片
            CameraInfo cameraInfo = new CameraInfo();
            cameraInfo.setCameraId(cameraId);
            cameraInfo = cameraInfoMapper.selectCameraInfo(cameraInfo);
            // 判断图片日期是7天前，需要重新获取
            if (cameraInfo != null && StringUtils.isNotBlank(cameraInfo.getCameraImage())
                    && DateUtils.isWithinSevenDays(cameraInfo.getImageDate())) {
                return cameraInfo.getCameraImage();
            }

            // 查询接口数据
            StreamPictureParams params = new StreamPictureParams();
            params.setCameraId(cameraId);
            // 图片时间
            params.setRequestTime(DateUtils.getOneMinutesAgo());
            // 生成规则为yyyyMMddHHmmss+四个随机字符
            params.setSerialNo(UUID.generateSerialNumber());
            StreamPictureResult result = haoYunService.realStreamPictureSync(params);

            if (result != null && StringUtils.isNotBlank(result.getScenneImage())) {

                if (!StringUtils.startsWithIgnoreCase(result.getScenneImage(),
                        "data:image/jpeg;base64")) {
                    result.setScenneImage("data:image/jpeg;base64," + result.getScenneImage());
                }

                // 更新数据库中图片
                cameraInfo = new CameraInfo();
                cameraInfo.setCameraImage(result.getScenneImage());
                cameraInfo.setCameraId(cameraId);
                cameraInfoMapper.updateCameraImage(cameraInfo);
                return result.getScenneImage();
            }

        } catch (BaseException be) {
            logger.error("queryCameraPicture error :", be);
            throw be;
        } catch (Exception e) {
            logger.error("queryCameraPicture error :", e);
        }
        throw new BaseException("获取图片失败");
    }

    /**
     * 新增摄像头管理
     *
     * @param cameraInfo 摄像头管理
     * @return 结果
     */
    @Override
    public int insertCameraInfo(CameraInfo cameraInfo) {
        cameraInfo.setCreateTime(DateUtils.getNowDate());
        // 判断摄像头编号是否已存在
        CameraInfo cameraInfo1 = new CameraInfo();
        cameraInfo1.setCameraId(cameraInfo.getCameraId());
        cameraInfo1.setStatus("0");
        cameraInfo1 = cameraInfoMapper.selectCameraInfo(cameraInfo1);
        if (cameraInfo1 != null) {
            throw new BaseException("摄像头编号已存在");
        }
        return cameraInfoMapper.insertCameraInfo(cameraInfo);
    }

    /**
     * 修改摄像头管理
     *
     * @param cameraInfo 摄像头管理
     * @return 结果
     */
    @Override
    public int updateCameraInfo(CameraInfo cameraInfo) {
        cameraInfo.setUpdateTime(DateUtils.getNowDate());
        // 判断摄像头编号是否已存在
        CameraInfo cameraInfo1 = new CameraInfo();
        cameraInfo1.setCameraId(cameraInfo.getCameraId());
        cameraInfo1.setStatus("0");
        cameraInfo1 = cameraInfoMapper.selectCameraInfo(cameraInfo1);
        if (cameraInfo1 != null && !cameraInfo1.getId().equals(cameraInfo.getId())) {
            throw new BaseException("摄像头编号已存在");
        }
        return cameraInfoMapper.updateCameraInfo(cameraInfo);
    }

    /**
     * 批量删除摄像头管理
     *
     * @param ids 需要删除的摄像头管理主键
     * @return 结果
     */
    @Override
    public int deleteCameraInfoByIds(Long[] ids) {
        return cameraInfoMapper.deleteCameraInfoByIds(ids);
    }

    /**
     * 查询摄像头管理
     *
     * @param id 摄像头管理主键
     * @return 摄像头管理
     */
    @Override
    public CameraInfo selectCameraInfoById(Long id) {
        return cameraInfoMapper.selectCameraInfoById(id);
    }


    @Override
    public boolean importCameraConfig(List<CameraInfo> cameraInfoList, String createBy) {
        try {
            List<String> errorList = new ArrayList<>();
            StringBuilder errorMsg = null;

            int succ = 0;

            int index = 0;
            // 遍历检查列表数据
            for (CameraInfo cameraInfo : cameraInfoList) {
                errorMsg = new StringBuilder();
                if (StringUtils.isBlank(cameraInfo.getCameraId()) || StringUtils.isBlank(
                        cameraInfo.getCameraName()) || StringUtils.isBlank(
                        cameraInfo.getDeptCode())) {
                    errorMsg.append("参数为空；");
                } else {
                    // 判断机构编号是否存在
                    SysDept sysDept = deptService.selectDeptByCode(cameraInfo.getDeptCode());
                    if (sysDept == null || StringUtils.equals("1", sysDept.getStatus())) {
                        errorMsg.append("机构编号：").append(cameraInfo.getDeptCode())
                                .append("不存在；");
                    }

                    // 摄像头编号是否已存在
                    CameraInfo cameraInfo1 = new CameraInfo();
                    cameraInfo1.setCameraId(cameraInfo.getCameraId());
                    cameraInfo1.setStatus("0");
                    cameraInfo1 = cameraInfoMapper.selectCameraInfo(cameraInfo1);
                    if (cameraInfo1 != null) {
                        errorMsg.append("摄像头编号：").append(cameraInfo.getCameraId())
                                .append("，在").append(cameraInfo1.getDeptCode())
                                .append("机构编号中；");
                    }
                }

                index++;
                if (StringUtils.isNotEmpty(errorMsg)) {
                    errorList.add("\n第" + index + "行错误：" + errorMsg
                            + "\n");
                } else {
                    cameraInfo.setCreateBy(createBy);
                    cameraInfo.setUpdateBy(createBy);
                    cameraInfo.setCreateTime(DateUtils.getNowDate());
                    cameraInfo.setUpdateTime(DateUtils.getNowDate());
                    if (StringUtils.isBlank(cameraInfo.getStatus()) || (
                            StringUtils.equals("0", cameraInfo.getStatus()) && StringUtils.equals(
                                    "1", cameraInfo.getStatus()))) {
                        cameraInfo.setStatus("0");
                    }
                    // 插入数据
                    cameraInfoMapper.insertCameraInfo(cameraInfo);
                    succ++;
                }
            }

            if (!CollectionUtils.isEmpty(errorList)) {
                errorList.add(0, "成功导入" + succ + "条数据；\n");
                throw new BaseException(errorList.toString());
            }

            return true;
        } catch (BaseException be) {
            throw be;
        } catch (Exception e) {
            logger.error("importCameraConfig error :", e);
        }
        return false;
    }
}
